﻿#include "downloadmq.h"
#include "qtredis.h"

#include <QDebug>

DownloadMQ* DownloadMQ::instance = nullptr;
QMutex DownloadMQ::mutex;
DownloadMQ::DownloadMQ(QObject *parent) : QObject(parent)
{
    
}

DownloadMQ::~DownloadMQ()
{
    foreach (auto item, map_downloadStore) {
        qDebug()<<"释放 "<<item.data;
        delete[] item.data;
    }
}

DownloadMQ *DownloadMQ::Instance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new DownloadMQ();
        }
        locker.unlock();
    }
    return instance;
}

void DownloadMQ::download(QString qurl)
{
    QMutexLocker locker(&dmutex);
    //判断这个url是否已经在任务列表里面，有则退出，等待下载完成
    if(set_downloadMQ.find(qurl) != set_downloadMQ.end())
    {
        locker.unlock();
        return;
    }
    
    //插入任务列表
    set_downloadMQ.insert(qurl);
    locker.unlock();
    
    //实例化下载器
    QTcpSocket *socket = new QTcpSocket();
    //DownloadManager* manager = new DownloadManager();    
    
    //下载完成之后，调用保存的槽函数
    connect(socket,&QTcpSocket::readyRead,this, [&](){
        //下载完毕
        QString fileName;
        QByteArray message = socket->readAll();
        QJsonParseError error;
        QJsonObject obj = QJsonDocument::fromJson(message).object();
        if(error.error != QJsonParseError::NoError)
        {
            QtRedis* redis = new QtRedis("chunsource.top",2022);
            if(redis->openConnection())
            {
                if(redis->auth("161100Me"))
                {
                    qDebug()<<"更新redis的值";
                    fileName = redis->get(qurl);
                    if(fileName.isEmpty())
                    {
                        socket->disconnectFromHost();
                        socket->close();
                        socket->deleteLater();
                        
                        return;
                    }
                }
            }
            redis->disconnectHost();
            redis->deleteLater();
        }else{
            fileName = obj["path"].toString();
        }
        
        socket->disconnectFromHost();
        socket->close();
        socket->deleteLater();
        
        
        QFile fl(fileName);
        QByteArray buffer;
        if(fl.open(QIODevice::ReadOnly))
        {
            buffer = fl.readAll();
        }else{
            return;
        }
        
        //分配文件内存
        char *data = new char[buffer.size()];
        memcpy(data,buffer.data(),buffer.size());
        
        //设置文件属性
        CFile file;
        file.data = data;
        file.size = buffer.size();
        file.len = buffer.size();
        
        map_downloadStore[qurl] = file;
    });
    
    //创建下载数据
    QUrl qturl(qurl);
    QJsonObject obj;
    obj.insert("path",qturl.path());
    obj.insert("url",qurl);
}

bool DownloadMQ::getFile(QString url, CFile &file)
{
    QMutexLocker locker(&dmutex);
    auto it = map_downloadStore.find(url);
    if( it != map_downloadStore.end())
    {
        file.data = it->data;
        file.size = it->size;
        file.len = it->len;
        locker.unlock();
        return true;
    }
    return false;
}
